const AppUtils = require('./appUtils').default;
const DZUtils = require('./DZUtils').default;

const helper = {};
module.exports = helper;

let next;

// 获取掌证宝webview的opstation
function getOpStationInZzb() {
  const opStation = { opStation: '' }; // 后端默认空字符串
  return new Promise((resolve, reject) => {
    // 超时5s报异常
    const timer = setTimeout(() => {
      clearTimeout(timer);
      reject(new Error('app回调异常'));
    }, 5000);
    window.setOpStationInfo = (data) => {
      clearTimeout(timer);
      if (data) {
        resolve({ code: '0', data });
      }
      reject(new Error('app返回opstation异常!'));
    };
    window.KDS_Native.getOpStationInfo('setOpStationInfo');
  }).then(results => {
    if (results.code === '0') {
      opStation.opStation = results.data || '';
      console.log('window.KDS_Native.getOpStationInfo...', JSON.stringify(opStation));
      DZUtils.setStorage('opStation', JSON.stringify(opStation));
    }
    // app3.9.5及以上版本支持dzPhoneParams
    return window.zzbNativeComm.otherExec.getAppVersion();
  })
    .then(data => {
      opStation.version = data.appVersion || 'app low version';
      opStation.appType = AppUtils.native.phoneType();
      DZUtils.setStorage('opStation', JSON.stringify(opStation));
      console.log('window.zzbNativeComm.otherExec.getAppVersion...', JSON.stringify(opStation));
      next && next();
    }).catch((err) => {
      console.log('getOpStationInZzb err', err);
      next && next();
    });
}

// 获取优品webview的opstation
function getOpStationInUp() {
  const opStation = { opStation: '' }; // 后端默认空字符串
  return new Promise((resolve, reject) => {
    // 超时5s报异常
    const timer = setTimeout(() => {
      clearTimeout(timer);
      reject(new Error('up回调异常'));
    }, 5000);
    window.upNativeComm.exec('APP.getVersion', {
      callback: (code, data) => {
        clearTimeout(timer);
        if (code == '0') {
          resolve(data);
        } else {
          reject(new Error('upNativeComm Error!'));
        }
      }
    });
  }).then(data => {
    data = JSON.parse(data);
    opStation.version = data.appVersion || 'app low version';
    opStation.appType = AppUtils.native.phoneType();
    DZUtils.setStorage('upSdkVersion', data.sdkVersion);
    DZUtils.setStorage('opStation', JSON.stringify(opStation));

    return new Promise((resolve, reject) => {
      // 超时5s报异常
      const timer = setTimeout(() => {
        clearTimeout(timer);
        reject(new Error('up回调异常'));
      }, 5000);
      window.upNativeComm.exec('APP.getUserInfo', {
        callback: (code, data2) => {
          clearTimeout(timer);
          if (code == '0') {
            resolve(data2);
          } else {
            reject(new Error('upNativeComm Error!'));
          }
        }
      });
    });
  }).then(data => {
    opStation.opStation = JSON.parse(data).opStation || '';
    DZUtils.setStorage('opStation', JSON.stringify(opStation));
    console.log('getOpStationInUp...', JSON.stringify(opStation));
    next && next();
  }).catch(error => {
    console.log(error);
    next && next();
  });
}

// get opstation for app
// 需要释放router钩子
helper.getOpStation = (callback) => {
  next = callback;
  const opStation = DZUtils.getStorage('opStation');
  // 可能存在外部跳转商城时，opStation已有值，但不是最新值的情况
  // 目前的入口，暂不考虑opStation不同的情况
  const hasTicket = window.location.href.indexOf('ticket') > -1;
  if (AppUtils.browser.isApp && (!opStation)) {
    console.log('hasTicket:', hasTicket);
    console.log('opStation:', opStation);
    // ios 进入到优品webview后再进入到掌证宝webview后，ua中同时包含thinkive和UPHybridSDK
    // android 优品webview和掌证宝webview分别包含thinkive和UPHybridSDK
    // 逻辑可统一为：优先判断是否有掌证宝hybrid api
    // ios window.app_init特殊处理
    if (AppUtils.browser.ios) {
      // 针对掌证宝容器
      window.app_init = () => {
        window.app_init = null;
        getOpStationInZzb();
      };
      // 针对优品容器，需引入优品的jssdk.js文件
      DZUtils.importScript({
        url: '/dz-mall/otc/front/lib/jssdk-app-1.0.1.min.js',
        flag: 'td-upsdk-flag',
        callback() {
          getOpStationInUp();
        }
      });
    }
    if (AppUtils.browser.android) { // 掌证宝
      if (!AppUtils.browser.isUpSdk) {
        getOpStationInZzb();
      } else {
        DZUtils.importScript({
          url: '/dz-mall/otc/front/lib/jssdk-app-1.0.1.min.js',
          flag: 'td-upsdk-flag',
          callback() {
            getOpStationInUp();
          }
        });
      }
    }
  } else if (AppUtils.browser.isUpSdk) {
    // 针对优品容器，需引入优品的jssdk.js文件
    DZUtils.importScript({
      url: '/dz-mall/otc/front/lib/jssdk-app-1.0.1.min.js',
      flag: 'td-upsdk-flag',
      callback: next
    });
  } else {
    next && next();
  }
};